<template>
  <div>
    <a-card title="库存报表">
      <a-form-model ref="form" :model="searchForm" :rules="rules" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
      <a-row gutter="16">

        <a-col :span="2" :md="6" :xl="4" style="margin-bottom: 12px;">
          <a-form-model-item label="仓库选择">
          <a-select v-model="searchForm.warehouse" placeholder="仓库" allowClear style="width: 100%;" @change="search">
            <a-select-option v-for="item in warehouseItems" :key="item.id" :value="item.id">{{item.name}}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        </a-col>
        <a-col :span="2" :md="2" :xl="4" style="margin-bottom: 12px;">
          <a-form-model-item label="库存情况">
          <a-select v-model="searchForm.has_stock" placeholder="库存状态" allowClear style="width: 100%;" @change="search">
            <a-select-option  :value="true">有库存</a-select-option>
            <a-select-option  :value="false">无库存</a-select-option>
          </a-select>
        </a-form-model-item>
        </a-col>
        <a-col :span="6" :md="6" :xl="4" style="margin-bottom: 12px;">
          <a-form-model-item label="搜索">
            <a-input-search v-model="searchForm.search" placeholder="产品编号/名称/规格" allowClear @search="search" />
          </a-form-model-item>
        </a-col>
        <a-col :span="6" :md="6" :xl="4" style="margin-bottom: 12px;">
            <a-form-model-item >
              <a-button-group> 
                <a-button type="primary" :loading="loading" @click="search"><a-icon type="search" />查询</a-button>    
                <a-button :loading="downloadLoading" @click="handleDownload"><a-icon type="file-excel" />导出</a-button>    
              </a-button-group>
            </a-form-model-item>
        </a-col>
        <!-- <a-col :span="24" :md="8" :xl="6" style="max-width: 256px; margin-bottom: 12px;">
          <a-range-picker @change="onChangePicker" />
        </a-col> -->
      </a-row>
    </a-form-model>
      <a-row style="margin-top: 12px;">
        <a-table size="small"
          rowKey="id"
          :columns="columns"
          :dataSource="items" 
          :loading="loading"
          :pagination="pagination"
          @change="tableChange">
        </a-table>
      </a-row>
    </a-card>
  </div>
</template>

<script>
  import { warehousesOption } from '@/api/option'
  import { inventoryReportList } from '@/api/report'
  import { List} from '@/api/common'
  import { datetimeToString} from "@/utils/common";
  export default {
    name: 'Warehouse',
    components: {
    },
    data() {
      return {
        downloadLoading: false,
        downloadList: [],
        columns: [
          {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
            customRender: (value, item, index) => {
              return (this.pagination.current-1)*this.pagination.pageSize+index + 1
            },
            width: 45
          },
          {
            title: '仓库',
            dataIndex: 'warehouse_name',
          },
          {
            title: '仓库编号',
            dataIndex: 'warehouse_number',
          },
          {
            title: '产品名称',
            dataIndex: 'goods_name',
          },
          {
            title: '规格',
            dataIndex: 'goods_spec',
          },
          {
            title: '单位',
            dataIndex: 'unit_name',
            width: 80
          },
          {
            title: '产品编号',
            dataIndex: 'goods_number',
          },
          // {
          //   title: '产品条码',
          //   dataIndex: 'goods_barcode',
          // },
          {
            title: '库存总数',
            dataIndex: 'total_quantity',
          },

          {
            title: '库存状态',
            dataIndex: 'has_stock',
            customRender: (value, item, index) => {
              return item.has_stock ? '有' : '无'
            },
          },
          // {
          //   title: '操作',
          //   dataIndex: 'action',
          //   scopedSlots: { customRender: 'action' },
          //   width: 147
          // },
        ],
        searchForm: { page: 1, page_size: 15 },
        pagination: { current: 1, total: 0, pageSize: 15 },
        loading: false,
        items: [],
        visible: false,
        targetItem: {},
        form: {},
      };
    },
    computed: {
    },
    methods: {

      handleDownload() {
        this.loading = true;
        this.downloadLoading = true;
        this.searchForm.page_size=9999
          List(this.searchForm,'inventories').then(response  => {
          const resp = response.data;        
          this.downloadList = response.results;
          let i=0
          this.downloadList.forEach(e => {
                  i+=1
                  e['index'] = i
                  e.has_stock = e.has_stock?'有库存':'无库存'
          });
          // this.downloadList.forEach(e => {
          //     e.jgry_items=this.jgry_items2names(e.jgry_items)
          //     e.is_void=e.is_void?'已作废':"正常"
          // });
          // console.log('this.downloadList:',this.downloadList )
          this.searchForm.page_size=15
          import("@/vendor/Export2ExcelNew").then(excel => {
            const tHeader1 = [
              "序号",
              "仓库编号",
              "仓库名称",
              "产品编号",
              "产品名称",
              "产品型号",
              "库存总数",              
              "库存状态",
            ];
            const filterVal = [
              "index",
              "warehouse_number",
              "warehouse_name",
              "goods_number",
              "goods_name",
              "goods_spec",
              "total_quantity",
              "has_stock",
            ];
            //const filterVal = tHeader;
            //不要将下载数据与显示数据列表用同一个变量，否则要出问题
            const list = this.downloadList;
            let downloadList = list;
  
            const data = this.formatJson(filterVal, downloadList);
            console.log('data:',data)
            const title = ["库存情况"+datetimeToString(new Date())];
            const sheetname = "库存情况";
            const merges = [ "A1:H1"];
            excel.export_json_to_excel({
              title,
              header: tHeader1,
              // multiHeader:[tHeader1],            
              data,
              filename: "库存情况"+datetimeToString(new Date()),
              merges,
              // autoWidth: this.autoWidth,
              autoWidth: this.autoWidth,
              bookType: this.bookType,
              sheetname
            });
            this.loading = false;
            this.downloadLoading = false;
          });
        });
      },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
      initialize() {
        warehousesOption({ page_size: 99999 }).then(resp => {
          this.warehouseItems = resp.results;
        });
        this.list();
      },
      list() {
        this.loading = true;
        inventoryReportList(this.searchForm).then(data => {
          this.pagination.total = data.count;
          this.items = data.results;
        }).finally(() => {
          this.loading = false;
        });
      },
      tableChange(pagination, filters, sorter) {
        console.log(pagination)
        this.searchForm.page = pagination.current;
        this.pagination.current = pagination.current;
        this.searchForm.ordering = `${sorter.order == 'descend' ? '-' : ''}${sorter.field}`;
        this.list();
      },
      onChangePicker(date, dateString) {
        let startDate = date[0], endDate = date[1];
        this.searchForm.start_date = startDate ? startDate.format('YYYY-MM-DD') : undefined;
        this.searchForm.end_date = endDate ? endDate.add(1, 'days').format('YYYY-MM-DD') : undefined;
        this.search();
      },
      search() {
        this.searchForm.page = 1;
        this.pagination.current = 1;
        this.list();
      },
    },
    mounted() {
      this.initialize();
    },
  }
</script>